package com.example.jmeter.service;

import com.example.jmeter.dependent.SoftDependInstall;
import com.example.jmeter.entity.TestPlan;
import com.example.jmeter.entity.ThreadGroup;
import com.example.jmeter.enums.DependType;
import com.example.jmeter.enums.JmeterCommand;
import com.example.jmeter.enums.JmxTemplate;
import com.example.jmeter.util.FileUtil;
import com.example.jmeter.util.FreeMarkerUtil;
import org.springframework.util.Assert;

import java.io.File;

/**
 * @program: spring-agent
 * @description:
 * @author: zt22328 赵儒定
 * @create: 2023-04-21 14:14
 **/
public class JmeterService {

    private static String JMX_TEMP;

    private static String REPORT_TEMP;

    static {
        String jmeterDir = System.getProperty("user.dir") + File.separator + "dependent" + File.separator + "Jmeter" + File.separator;
        JMX_TEMP = jmeterDir + "jmx" + File.separator;
        REPORT_TEMP = jmeterDir + "report" + File.separator;
    }

    public void generateJmx(TestPlan testPlan, JmxTemplate template) {
        template.checkTestPlan(testPlan);
        String jmxName = testPlan.getName() + ".jmx";
        String jmxFile = JMX_TEMP + jmxName;
        FreeMarkerUtil.ftlTempGenerate("/template", template.getTemplate(), testPlan, jmxFile);
        Assert.isTrue(FileUtil.exists(jmxFile), "jmx生成失败");
    }

    public void execute(String planName) {
        this.execute(planName, null, null);
    }

    public void execute(String planName, Integer threads, Integer loops) {
        String jmxFile = JMX_TEMP + planName + ".jmx";
        String jtl = planName + ".jtl";
        Assert.isTrue(FileUtil.exists(jmxFile), "jmx文件不存在");
        File report = new File(REPORT_TEMP + planName);
        if (report.exists()) {
            report.renameTo(new File(report.getName() + "_" + System.currentTimeMillis()));
        } else {
            if (!report.getParentFile().exists()) {
                report.getParentFile().mkdirs();
            }
        }
        SoftDependInstall softDepend = new SoftDependInstall(DependType.Jmeter);
        String command = JmeterCommand.STANDALONE_TEST_PLAN.getCommand(jmxFile, jtl,
                REPORT_TEMP + planName, threads, loops);
        softDepend.execute(command, "summary");
    }

}
